﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using NLog;
using SellAvi.Model;

namespace SellAvi.Classes
{
    public class TaskMailSender : AvitoTask
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
        private readonly AvitoMailingItem _avitoMailItem;
        private readonly AvitoTaskStatus _avitoTaskStatus;
        private string _token_n;
        private string _token_v;
        public TaskMailSender(AbstractModel am)
            : base(am)
        {
            _avitoMailItem = am as AvitoMailingItem;
            _avitoTaskStatus = new AvitoTaskStatus();
        }

        public override string TaskName
        {
            get { return "сообщение"; }
        }

        public override string TaskDescription
        {
            get { return _avitoMailItem.MessageText; }
        }

        public override List<OperationDelegate> TaskExecutionPlan
        {
            get
            {
                return new List<OperationDelegate>()
            {
                PublicationTimeout,
                SetMailToken,
                SendMessage,
                //OpenChatRoom
            };
            }
        }

        public override string TaskCompletedUrl
        {
            get { return ("https://www.avito.ru/profile/messenger/channel/" + _avitoMailItem.ChatRoomId); }
        }

        /// <summary>
        /// Предварительная задержка перед отправкой 
        /// </summary>
        private AvitoTaskStatus PublicationTimeout()
        {
            var commandName = String.Format("Отправка сообщения через {0} секунд ...", TaskDelay);
            Logger.Trace(commandName);
            _avitoTaskStatus.OperationStartTime = DateTime.Now;
            _avitoTaskStatus.OperationMessage = commandName;
            Thread.Sleep(1000);
            TaskDelay--;
            _avitoTaskStatus.OperationSucceeded = true;
            _avitoTaskStatus.OperationRepeatNeeded = (TaskDelay > 0) ? true : false;
            return _avitoTaskStatus;
        }
        /// <summary>
        /// Предварительный переход на страницу с объявлением для получения токена 
        /// </summary>
        private AvitoTaskStatus SetMailToken()
        {
            var commandName = "Переход на страницу объявления для получения нового Token";
            Logger.Trace(commandName);
            _avitoTaskStatus.OperationStartTime = DateTime.Now;
            _avitoTaskStatus.OperationMessage = commandName;
            var str = WebClient.DownloadString(new Uri(_avitoMailItem.SendToUrl));

            var reg = new Regex(@"name=\""(?<token_name>token\[\d+\])""\svalue=\""(?<token_value>\w+)\""").Match(str);
            var tn = reg.Groups["token_name"].Value;
            var tv = reg.Groups["token_value"].Value;
            if (String.IsNullOrEmpty(tn) || String.IsNullOrEmpty(tv))
            {
                _avitoTaskStatus.OperationSucceeded = false;
                _avitoTaskStatus.ErrorCode = 311;
            }
            else
            {
                Logger.Debug("Полученые значения token_name={0} token_value={1}", tn, tv);
                _token_n = tn;
                _token_v = tv;
                _avitoTaskStatus.OperationSucceeded = true;
            }
            return _avitoTaskStatus;
        }

        private AvitoTaskStatus SendMessage()
        {
            var commandName = "Отправка сообщения";
            Logger.Trace(commandName);
            _avitoTaskStatus.OperationStartTime = DateTime.Now;
            _avitoTaskStatus.OperationMessage = commandName;

            string boundary = "------------------------" + DateTime.Now.Ticks.ToString("x");
            WebClient.DefaultHeaders[HttpRequestHeader.ContentType] = "multipart/form-data; boundary=" + boundary;
            var package = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n--{0}\r\nContent-Disposition: form-data; name=\"comment\"\r\n\r\n{3}\r\n--{0}\r\nContent-Disposition: form-data; name=\"subscribe-position\"\r\n\r\n2\r\n--{0}\r\n", boundary, _token_n, _token_v, _avitoMailItem.MessageText);
            var nfile = WebClient.Encoding.GetBytes(package);
            var postUrl = String.Format("https://www.avito.ru/items/write/{0}", _avitoMailItem.AdId);
            var resp = Encoding.Default.GetString(WebClient.UploadData(postUrl, "POST", nfile));

            var reg = new Regex(@"chatRoomId\"":\""(?<room_id>[-\w+]+)\""").Match(resp);
            var room_id = reg.Groups["room_id"].Value;
            if (String.IsNullOrEmpty(room_id))
            {
                _avitoTaskStatus.OperationSucceeded = false;
                _avitoTaskStatus.ErrorCode = 321;
                _avitoMailItem.ChatRoomId = room_id;
            }
            else
            {
                Logger.Debug("Получено значение chatRoomId={0}", room_id);
                _avitoTaskStatus.OperationSucceeded = true;
            }

            return _avitoTaskStatus;

        }

        //private AvitoTaskStatus OpenChatRoom()
        //{
        //    var commandName = "Переход на страницу объявления для получения нового Token";
        //    Logger.Trace(commandName);
        //    _avitoTaskStatus.OperationStartTime = DateTime.Now;
        //    _avitoTaskStatus.OperationMessage = commandName;

        //    //TaskCompletedUrl = "";
        //    //var str = WebClient.DownloadString(new Uri("https://www.avito.ru/profile/messenger/channel/u2i-847364335-39185144"));


        //    return _avitoTaskStatus;

        //}


    }
}
